package com.aiti.lulian.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.utils.message.Message;
import com.aiti.base.core.utils.stringUtil.StringUtil;
import com.aiti.lulian.entity.*;
import com.aiti.lulian.entity.crad.PayRemoteAddRoleFail;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.mapper.CardVipRecordMapper;
import com.aiti.lulian.mapper.card.PayRemoteAddRoleFailMapper;
import com.aiti.lulian.pay.dto.CardVipRecordDto;
import com.aiti.lulian.pay.model.CardVipRecord;
import com.aiti.lulian.pay.vo.CardVipRecordVo;
import com.aiti.lulian.service.*;
import com.aiti.lulian.utils.RandomCharUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class CardVipRecordServiceImpl extends BaseSerivceImpl<CardVipRecordMapper, CardVipRecord> implements ICardVipRecordService {

    @Autowired
    private CardVipRecordMapper cardVipRecordMapper;

    @Autowired
    private ILulianEnterpriseHistoryService historyService;

    @Autowired
    private ILuLianEnterpriseService enterpriseService;

    @Autowired
    private CloudShowManagerSubService managerSubService;

    @Autowired
    private PayRemoteAddRoleFailMapper payRemoteAddRoleFailMapper;

    @Autowired
    private ILuLianEnterpriseExtensionService luLianEnterpriseExtensionService;

    @Autowired
    private IEnterpriseDictDataService enterpriseDictDataService;

    @Autowired
    private ISysDataService sysDataService;

    @Override
    public Message getConfirmationCode(String enterpriseId) {
        //根据企业ID查询当前企业是否存在与确认码的关联记录
        CardVipRecord cardVipRecord = cardVipRecordMapper.selectOne(new LambdaQueryWrapper<CardVipRecord>()
                .eq(CardVipRecord::getPayType, "3")
                .eq(CardVipRecord::getEnterpriseId, enterpriseId)
                .isNotNull(CardVipRecord::getConfirmationCode));
        if (cardVipRecord == null) {
            //若不存在关联记录则标记为未确认转账状态，并随机生成一个唯一确认码进行返回
            cardVipRecord = new CardVipRecord();
            cardVipRecord.setEnterpriseId(enterpriseId);
            cardVipRecord.setPayType("3");
            cardVipRecord.setConfirmationCode(generateConfirmationCode());
            cardVipRecord.setOrderStatus("0");
            //查询当前企业是否已进行了别的支付方式
        }
        return Message.success(cardVipRecord);
    }

    @Override
    public Message confirm(CardVipRecordDto cardVipRecordDto) {
        CardVipRecord cardVipRecord = new CardVipRecord();
        BeanUtils.copyProperties(cardVipRecordDto, cardVipRecord);
        //校验当前企业是否确认过转账
        CardVipRecord obj = cardVipRecordMapper.selectOne(new LambdaQueryWrapper<CardVipRecord>()
                .eq(CardVipRecord::getEnterpriseId, cardVipRecord.getEnterpriseId())
                .eq(CardVipRecord::getPayType, "3"));
        if (obj != null) {
            //若已确认过则进行提示
            return Message.fail("当前企业已确认过转账");
        }
        //对于第一次确认已转账的企业，将其与确认码的关联记录进行保存
        cardVipRecord.setBaseCreateTime(new Date());
        cardVipRecord.setPayType("3");
        boolean isBasicsVersion = StrUtil.equals(cardVipRecord.getVipLevel(), "1");
        cardVipRecord.setVipLevel(isBasicsVersion ? "基础版" : "高级版");
        cardVipRecord.setPayAmount(isBasicsVersion ? ((long) 150000) : ((long) 1500000));
        cardVipRecord.setOrderStatus("4");
        int insert = cardVipRecordMapper.insert(cardVipRecord);
        if (insert > 0) {
            return Message.success("确认成功");
        } else {
            return Message.fail("确认失败");
        }
    }

    @Override
    public List<CardVipRecordVo> getList(CardVipRecordDto cardVipRecordDto, Page<CardVipRecord> page) {
        return cardVipRecordMapper.selectListCustom(cardVipRecordDto, page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message open(CardVipRecordDto cardVipRecordDto) {
        CardVipRecord cardVipRecord = new CardVipRecord();
        BeanUtils.copyProperties(cardVipRecordDto, cardVipRecord);
        cardVipRecord.setOrderStatus("1");
        cardVipRecord.setPayTime(new Date());
        //更新记录
        boolean update = this.updateById(cardVipRecord);
        //将show_enterprise_history中的对应数据添至show_enterprise表中
        String enterpriseId = cardVipRecordDto.getEnterpriseId();
        LuLianEnterprise enterprise = enterpriseService.getById(enterpriseId);
        if(enterprise == null) {
            LuLianEnterpriseHistory history = historyService.getById(enterpriseId);
            if (history == null) {
                return Message.fail("该企业暂无企业认证记录，请先校验数据的完善性");
            }
            LuLianEnterprise luLianEnterprise = new LuLianEnterprise();
            BeanUtil.copyProperties(history, luLianEnterprise);
            luLianEnterprise.setMiniProgramVersion(StrUtil.equals(cardVipRecordDto.getVipLevel(), "基础版") ? 1 : 2);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.YEAR, 1);
            luLianEnterprise.setExpireTime(calendar.getTime());
            luLianEnterprise.setPayChannel(3);
            boolean save = enterpriseService.save(luLianEnterprise);
            if (! save) {
                update = false;
            }
        } else {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.YEAR, 1);
            enterprise.setExpireTime(calendar.getTime());
            enterprise.setPayChannel(3);
            enterprise.setMiniProgramVersion(StrUtil.equals(cardVipRecordDto.getVipLevel(), "基础版") ? 1 : 2);
            enterpriseService.updateById(enterprise);
        }
        LuLianEnterpriseExtension extension = luLianEnterpriseExtensionService.getOne(new LambdaQueryWrapper<LuLianEnterpriseExtension>().eq(LuLianEnterpriseExtension::getEnterpriseId, enterpriseId));
        if (extension == null) {
            LuLianEnterpriseExtension build = LuLianEnterpriseExtension.builder().enterpriseId(enterpriseId).build();
            luLianEnterpriseExtensionService.save(build);
        }
        if (! StringUtil.equals(cardVipRecord.getVipLevel(), "基础版")) {
            List<EnterpriseDictData> enterpriseDictDataList = enterpriseDictDataService.list(new LambdaQueryWrapper<EnterpriseDictData>().eq(EnterpriseDictData::getEnterpriseId, enterpriseId));
            if (enterpriseDictDataList.size() == 0) {
                List<SysData> cardCustomerTypeList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "CARD_CUSTOMER_TYPE")
                        .orderByAsc(SysData::getBaseId));
                List<SysData> cardCustomerSourceList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "CARD_CUSTOMER_SOURCE")
                        .orderByAsc(SysData::getBaseId));
                List<SysData> cardCustomerFollowStatusList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "CARD_CUSTOMER_FOLLOW_STATUS")
                        .orderByAsc(SysData::getBaseId));
                int i = 0;
                int j = 0;
                int k = 0;
                List<EnterpriseDictData> dataList = new ArrayList<>();
                //默认的客户类型
                for (SysData cardCustomerType : cardCustomerTypeList) {
                    EnterpriseDictData cardCustomerTypeDictData = EnterpriseDictData.builder().dictTypeNo(cardCustomerType.getDictTypeNo()).dictTypeName("客户类型").baseName(cardCustomerType.getBaseName()).typeId(cardCustomerType.getTypeId())
                            .sort(i ++).isUpdated(StrUtil.equals(cardCustomerType.getBaseId(), "7ee01fe48a2647eb8b549acd28c45899") ? "0" : "1").module("8725839a-1488-4c30-9ef4-6d7369e28f00,8725839a-1488-4c30-9ef4-6d7369e28f01")
                            .enterpriseId(enterpriseId).creator("1").baseCreateTime(new Date()).build();
                    dataList.add(cardCustomerTypeDictData);
                }
                //默认的客户来源
                for (SysData cardCustomerSource : cardCustomerSourceList) {
                    EnterpriseDictData cardCustomerSourceDictData = EnterpriseDictData.builder().dictTypeNo(cardCustomerSource.getDictTypeNo()).dictTypeName("客户来源").baseName(cardCustomerSource.getBaseName()).typeId(cardCustomerSource.getTypeId())
                            .sort(j ++).isUpdated("1").module("8725839a-1488-4c30-9ef4-6d7369e28f00,8725839a-1488-4c30-9ef4-6d7369e28f01")
                            .enterpriseId(enterpriseId).creator("1").baseCreateTime(new Date()).build();
                    dataList.add(cardCustomerSourceDictData);
                }
                //默认的跟进状态
                for (SysData cardCustomerFollowStatus : cardCustomerFollowStatusList) {
                    EnterpriseDictData cardCustomerFollowStatusDictData = EnterpriseDictData.builder().dictTypeNo(cardCustomerFollowStatus.getDictTypeNo()).dictTypeName("跟进状态").baseName(cardCustomerFollowStatus.getBaseName()).typeId(cardCustomerFollowStatus.getTypeId())
                            .sort(k ++).isUpdated((StrUtil.equals(cardCustomerFollowStatus.getBaseId(), "c661b397f83a4fd590f3c79ac4040dad1") || StrUtil.equals(cardCustomerFollowStatus.getBaseId(), "c661b397f83a4fd590f3c79ac4040dad4")) ? "0" : "1").module("8725839a-1488-4c30-9ef4-6d7369e28f00,8725839a-1488-4c30-9ef4-6d7369e28f01,8725839a-1488-4c30-9ef4-6d7369e28f03,8725839a-1488-4c30-9ef4-6d7369e28f04")
                            .enterpriseId(enterpriseId).creator("1").baseCreateTime(new Date()).build();
                    dataList.add(cardCustomerFollowStatusDictData);
                }
                enterpriseDictDataService.saveBatch(dataList);
            }
        }
        //将该用户角色从个人提升至企业管理员
        Map<String,String> params = new HashMap<>(16);
        params.put("userId", cardVipRecordDto.getUserId());
        params.put("roleId", "043ea2e3e02c4aa591df1f83e65069bc");
        Message message = managerSubService.addUserRole(params);
        if(message.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)) {
            //如果远程调用失败，则
            PayRemoteAddRoleFail build = PayRemoteAddRoleFail.builder()
                    .baseId(IdUtil.simpleUUID())
                    .userId(cardVipRecordDto.getUserId())
                    .roleId("043ea2e3e02c4aa591df1f83e65069bc")
                    .build();
            payRemoteAddRoleFailMapper.insert(build);
        }
        if (update) {
            return Message.success("开通成功");
        } else {
            return Message.fail("开通失败");
        }
    }

    /**
     * 生成唯一的确认码
     */
    private String generateConfirmationCode() {
        String confirmationCode = RandomCharUtil.generateRandomCode(6);
        while (isExist(confirmationCode)) {
            confirmationCode = RandomCharUtil.generateRandomCode(6);
        }
        return confirmationCode;
    }

    /**
     * 校验当前确认码在库中是否已存在
     */
    private boolean isExist(String confirmationCode) {
        CardVipRecord cardVipRecord = cardVipRecordMapper.selectOne(new LambdaQueryWrapper<CardVipRecord>().eq(CardVipRecord::getConfirmationCode, confirmationCode));
        if (cardVipRecord == null) {
            return false;
        } else {
            return true;
        }
    }
}